<template>
  <el-dialog
    v-model="visible"
    :close-on-click-modal="false"
    :title="$t('form.batchEdit.title')"
    width="600px"
    @closed="handleClose"
  >
    <div class="batch-edit-container">
      <!-- 提示信息 -->
      <el-alert
        :closable="false"
        show-icon
        type="info"
      >
        <template #default>
          <div>{{ $t("form.batchEdit.warning") }}</div>
          <div>{{ $t("form.batchEdit.supportTypes") }}</div>
          <div>{{ $t("form.batchEdit.unsupportedFields") }}</div>
        </template>
      </el-alert>

      <!-- 编辑数量提示 -->
      <div class="edit-count mt-4">
        {{ $t("form.batchEdit.editCount") }}
        <span class="primary-text">{{ selectedRows.length }}</span>
        {{ $t("form.batchEdit.records") }}
      </div>
      <!-- 编辑字段列表 -->
      <div class="edit-fields">
        <div
          v-for="(field, index) in editFields"
          :key="index"
          class="edit-field-item"
        >
          <div class="field-header">
            <span>{{ $t("form.batchEdit.selectField") }}</span>
            <el-button
              link
              type="danger"
              @click="removeField(index)"
            >
              {{ $t("common.delete") }}
            </el-button>
          </div>

          <!-- 字段选择 -->
          <el-select
            v-model="field.fieldKey"
            :placeholder="$t('form.batchEdit.pleaseSelectField')"
            class="w-full mb-3"
            size="default"
            @change="(value: any) => handleFieldChange(value, index)"
          >
            <el-option
              v-for="item in availableFields"
              :key="item.value"
              :disabled="selectedFieldKeys.includes(item.value) && item.value !== field.fieldKey"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <!-- 字段值输入 -->
          <form-item-value-selector
            v-model="field.value"
            :field="availableFields.find(item => item.value === field.fieldKey)"
            @change-label="label => handleChangeLabel(field.fieldKey, label)"
          />
        </div>
      </div>

      <!-- 添加字段按钮 -->
      <el-button
        :icon="Plus"
        class="mt-4"
        size="default"
        @click="addField"
      >
        {{ $t("form.batchEdit.addField") }}
      </el-button>
    </div>

    <!-- 操作按钮 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">{{ $t("common.cancel") }}</el-button>
        <el-button
          :loading="loading"
          type="primary"
          @click="handleConfirm"
        >
          {{ $t("common.confirm") }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import type { PropType } from "vue";
import { computed, reactive, ref } from "vue";
import { Plus } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { batchUpdateFormRequest, FieldItem } from "@/api/project/form";
import FormItemValueSelector from "@/views/components/FormItemValueSelector/index.vue";
import { useI18n } from "vue-i18n";

const props = defineProps({
  selectedRows: {
    type: Array,
    default: () => []
  },
  fields: {
    type: Array as PropType<FieldItem[]>,
    default: () => []
  },
  authGroupId: {
    type: Object,
    default: () => {}
  },
  formKey: {
    type: String,
    default: ""
  }
});

const emit = defineEmits(["update", "close"]);

const visible = ref(false);
const loading = ref(false);
const { t } = useI18n();

// 可选的字段列表
const availableFields = computed(() => {
  return props.fields
    .filter(
      (item: FieldItem) =>
        ["INPUT", "TEXTAREA", "NUMBER", "SELECT", "RADIO", "CHECKBOX", "CASCADER", "DATE"].includes(item.type || "") &&
        item.scheme &&
        !isHasLimit(item)
    )
    .map((item: FieldItem) => {
      return {
        ...item,
        value: item.value.replace("label", "")
      };
    });
});

// 判断是否有名额 或者不能重复的设置
const isHasLimit = (field: FieldItem) => {
  return (
    field.scheme?.config?.options?.filter((e: any) => {
      return typeof e.quotaSetting === "number";
    })?.length || field.scheme?.notRepeat
  );
};

// 获取已选中的字段
const selectedFieldKeys = computed(() => {
  return editFields.map(field => field.fieldKey).filter(Boolean);
});

// 编辑字段列表
const editFields = reactive<{ fieldKey: string; value: any }[]>([]);

// 字段值对象
const fieldValues = reactive<Record<string, any>>({});

// 处理字段选择变化
const handleFieldChange = (value: string, index: number) => {
  const oldKey = editFields[index].fieldKey;
  if (oldKey) {
    delete fieldValues[oldKey];
    delete fieldValues[oldKey + "label"];
  }
  editFields[index].fieldKey = value;
  editFields[index].value = "";
};

// 添加编辑字段
const addField = () => {
  editFields.push({ fieldKey: "", value: "" });
};

// 删除编辑字段
const removeField = (index: number) => {
  const field = editFields[index];
  if (field.fieldKey) {
    delete fieldValues[field.fieldKey];
  }
  editFields.splice(index, 1);
};

const handleChangeLabel = (fieldKey: string, label: string | string[]) => {
  fieldValues[fieldKey + "label"] = label;
};

// 处理确认
const handleConfirm = async () => {
  // 验证
  if (editFields.some(field => !field.fieldKey || !field.value)) {
    ElMessage.warning(t("form.batchEdit.pleaseCompleteFields"));
    return;
  }

  try {
    loading.value = true;
    // 构建更新数据
    editFields.forEach(field => {
      fieldValues[field.fieldKey] = field.value;
    });
    const updates = { ...fieldValues };
    console.log(updates);
    await batchUpdateFormRequest({
      formKey: props.formKey,
      dataIdList: props.selectedRows,
      authGroupId: props.authGroupId,
      originalData: updates
    });

    ElMessage.success(t("form.batchEdit.updateSuccess"));
    emit("update");
    visible.value = false;
  } catch (error: any) {
    ElMessage.error(t("form.batchEdit.updateFailed") + error.message);
  } finally {
    loading.value = false;
  }
};

// 处理关闭
const handleClose = () => {
  editFields.splice(0, editFields.length, { fieldKey: "", value: "" });
  emit("close");
};

// 暴露方法给父组件
defineExpose({
  show: () => (visible.value = true)
});
</script>

<style scoped>
.batch-edit-container {
  padding: 0 20px;
}

.edit-count {
  margin: 16px 0;
}

.primary-text {
  color: var(--el-color-primary);
  font-weight: bold;
}

.edit-field-item {
  margin-bottom: 20px;
  padding: 16px;
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 4px;
}

.field-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.mt-4 {
  margin-top: 16px;
}

.mb-3 {
  margin-bottom: 12px;
}

.w-full {
  width: 100%;
}
</style>
